import React, {useEffect, useMemo, useState} from 'react';
import {Menu, Layout} from "antd";
import type {MenuProps} from 'antd'
import {DatabaseOutlined, HomeOutlined} from "@ant-design/icons";
import {useLocation, useNavigate} from "react-router-dom";
import {renderMenuItem} from "@/routes";

const {Sider} = Layout;

type MenuItem = Required<MenuProps>['items'][number];

function getItem(
    label: React.ReactNode,
    key: React.Key,
    icon?: React.ReactNode,
    children?: MenuItem[],
): MenuItem {
    return {
        key,
        icon,
        children,
        label,
    } as MenuItem;
}

// const items: MenuItem[] = [
//     getItem('主页', '/', <HomeOutlined />),
//     getItem('数据管理', 'sub1', <DatabaseOutlined />, [
//         getItem('数据字典', '/cmn/dict')
//     ]),
// ];
function IndexSider() {
    const [collapsed,setCollapsed] = useState<boolean>(false);
    const navigate = useNavigate();
    const {pathname} = useLocation();
    const items: MenuItem[] = useMemo(() => {
        return renderMenuItem().map((item: any) => {
            let childrenItem;
            if (item.children) {
                childrenItem = item.children.filter((v:any) => !v.isHide).map((item: any) => {
                    return getItem(item.label, item.path);
                })
            }
            return getItem(item.label, item.path, item.icon, childrenItem);
        }, [])
    },[])

    const [keys,setKeys] = useState<string>("/"+pathname.split("/")[1]);
    // console.log("pathname------" + pathname)
    // 2- 将获取的path作为keys状态的值
    useEffect(()=>{
        setKeys("/"+pathname.split("/")[1]);
    },[pathname])

    return (
        <Sider breakpoint={"md"} collapsible collapsed={collapsed} onCollapse={value => setCollapsed(value)}>
            <div className="logo">
                <img src={require("@/assets/img/logo.png")} alt=""/>
                <span style={{display: collapsed ? "none" : "inline-block"}}>尚医通管理系统</span>
            </div>
            <Menu onClick = {({key})=> {
                navigate(key);
            }} theme="dark"
                // 当前展开的 SubMenu 菜单项 key 数组
                  openKeys={[keys]}

                // 3-SubMenu 展开/关闭的回调
                  onOpenChange={(openKeys: string[])=>{
                      // console.log(openKeys,"0000")
                      setKeys(openKeys[1]);
                  }}
                 selectedKeys={[pathname]} mode="inline" items={items}/>


        </Sider>
    );
}

export default IndexSider;